﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using JiraGenCommon.JiraServices;
using JiraGenCommon.Model;

public sealed class UtilsHelper
{
    public static string RefineEstimationToDefault(string originalEstimate)
    {
        return RefineEstimation(originalEstimate, 'h');
    }

    public static string RefineEstimation(string originalEstimate, char surfFixCharacter)
    {
        if (originalEstimate.IndexOf('w') == -1
            && originalEstimate.IndexOf('d') == -1
            && originalEstimate.IndexOf('h') == -1)
        {
            return string.Format("{0}{1}", originalEstimate, surfFixCharacter);
        }

        return originalEstimate;
    }

    public static string RefineSheetName(string sheetName)
    {
        sheetName = sheetName.Replace("\'", "");
        return sheetName.TrimEnd('$');
    }

    public static string GetStringField(object value)
    {
        return value == null ? string.Empty : value.ToString();
    }

    public static string GetStringWithLength(object value, int maxLength)
    {
        if (value == null) return string.Empty;

        var result = value.ToString();

        return result.Length > maxLength ? result.Substring(0, maxLength) : result;
    }

    public static string ConvertTimeSpentToUserString(long timeSpentInSecond)
    {
        var spentHour = timeSpentInSecond/(decimal)3600;
        return string.Format("{0}h", Math.Round(spentHour,2));
    }

    public static Dictionary<string, string> GetDevEffort(ICollection<JiraTask> syncList)
    {
        var results = new Dictionary<string, string>();
        foreach (var jiraTask in syncList)
        {
            var workLogs = JiraService.Instance.GetWorklogs(jiraTask.JiraKey);

            if (workLogs != null)
            {
                var timeSpent = workLogs.Sum(remoteWorklog => remoteWorklog.timeSpentInSeconds);
                if (results.ContainsKey(jiraTask.JiraKey))
                {
                    results[jiraTask.JiraKey] = ConvertTimeSpentToUserString(timeSpent);
                }
                else
                {
                    results.Add(jiraTask.JiraKey, ConvertTimeSpentToUserString(timeSpent));    
                }
            }
            else
            {
                if (results.ContainsKey(jiraTask.JiraKey))
                {
                    results[jiraTask.JiraKey] = "Not Specified";
                }
                else
                {
                    results.Add(jiraTask.JiraKey, "Not Specified");
                }
                
            }
        }

        return results;
    }
}
